//
//  ST_ChatMatchedView.swift
//  btvideo
//
//  Created by mac on 2020/7/9.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON


class ST_ChatMatchedView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(heart_image_view)
        heart_image_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(50)
        }
        
        self.addSubview(left_image_view)
        left_image_view.snp.makeConstraints { (make) in
            make.centerY.equalTo(heart_image_view)
            make.right.equalTo(heart_image_view.snp.left).offset(-20/375.0*ScreenWidth)
            make.width.height.equalTo(avatar_width)
        }
        
        
        self.addSubview(right_image_view)
        right_image_view.snp.makeConstraints { (make) in
            make.centerY.equalTo(heart_image_view)
            make.left.equalTo(heart_image_view.snp.right).offset(20/375.0*ScreenWidth)
            make.width.height.equalTo(avatar_width)
        }
        
        
        self.addSubview(redBox)
        redBox.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(heart_image_view.snp.bottom).offset(60)
            make.bottom.equalToSuperview().offset(-15)
        }
        
        redBox.addSubview(match_value_label)
        match_value_label.snp.makeConstraints { (make) in
            make.right.top.equalToSuperview()
            make.height.equalTo(26)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    fileprivate lazy var heart_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("首页_icon_配对成功_red"))
          return control
      }()
    
    fileprivate lazy var left_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = avatar_width/2.0
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_user_center))
        
        control.addGestureRecognizer(tap)
        
        control.isUserInteractionEnabled = true
        return control
    }()

    fileprivate let avatar_width = 90.cgFloat
    
    fileprivate lazy var right_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = avatar_width/2.0
        return control
    }()
    
    fileprivate lazy var redBox:UIView = {
       let control = UIView()
        control.backgroundColor = .white
        control.borderColor = UIColor.init(hex: 0xFF1F56)
        control.borderWidth = 1
        control.cornerRadius = 10
        return control
    }()
    
    fileprivate lazy var red_box_item_array = [MatchedValueLabel]()
    
    fileprivate lazy var match_value_label:MatchedCornerLabel = {
       let control = MatchedCornerLabel()
        return control
    }()
    
    var model:ST_ChatMatchedViewModel?{
        didSet{
            
            guard let m = model else { return  }
            
            match_value_label.match_rate = m.match_rate
            
            red_box_item_array.forEach({$0.removeFromSuperview()})
            
            var lastView:MatchedValueLabel?
            
            for item in m.match_message_attr_array{
                
                let v = MatchedValueLabel()
                v.attrStr = item
                redBox.addSubview(v)
                
                v.snp.makeConstraints { (make) in
                    make.left.equalToSuperview()
                    make.right.equalToSuperview()
                    make.height.equalTo(MatchedValueLabel.height)
                    if let last = lastView{
                        make.top.equalTo(last.snp.bottom).offset(5)
                    }else{
                        make.top.equalToSuperview().offset(10)
                    }
                }
                red_box_item_array.append(v)
                lastView = v
            }
            
            
            if let info = BINP.fetch_nickname_with_avatar(userId: sessionId){
                
                left_image_view.pin_setImage(from: info.avatar.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            }
            
            if let url = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.avatar{
                
                right_image_view.pin_setImage(from: url.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
                
            }
            
        }
    }
    
    var sessionId = ""
    
    
    
    @objc func push_user_center(){
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = self.sessionId

        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
    }
}



fileprivate class MatchedCornerLabel:UIView{
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(back_image_view)
        back_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(7)
            make.width.equalTo(30)
            make.height.equalTo(15)
            make.centerY.equalToSuperview()
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(imageView.snp.right).offset(3)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-5)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hex: 0xFF1F56)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        return control
    }()
    

    fileprivate lazy var imageView:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("匹配度_icon"))
          return control
      }()
    
    
    fileprivate lazy var back_image_view:UIImageView = {
      let control = UIImageView.init(image: ST_ImageUtils.imageName("匹配对_back_icon"))
        return control
    }()
    
    
    
    var match_rate = 0{
        didSet{
            titleLabel.text = match_rate.string + "%"
        }
    }
    
}


fileprivate class MatchedValueLabel:UIView{
    
    static let height = 20.cgFloat
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.width.equalTo(6)
            make.height.equalTo(6)
            make.centerY.equalToSuperview()
        }
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(imageView.snp.right).offset(5)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(5)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        return control
    }()
    

    fileprivate lazy var imageView:UIView = {
        let control = UIView()
        control.cornerRadius = 6/2.0
        control.backgroundColor = UIColor.init(hex: 0xFF1F56)
        return control
      }()
    
    var attrStr = NSAttributedString(){
        didSet{
            titleLabel.attributedText = attrStr
        }
    }
    
}


struct ST_ChatMatchedViewModel {
    
    var match_message:[String]
    var match_rate:Int
    
    var match_message_attr_array:[NSAttributedString]
    
    var header_height = 235.cgFloat
    
    init(json:JSON) {
        
        match_message = json["match_message"].arrayValue.map{$0.stringValue}
        
        match_rate = json["match_rate"].intValue
        
        var array = [NSAttributedString]()
        
//        let normalAttr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
//        let highlightAttr: [NSMutableAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 1, green: 0.12, blue: 0.34,alpha:1.000000)]
        var height = 130.cgFloat
        for item in match_message {
            
            let str = ST_ChatMatchedViewModel.createAttr(text: item)
                
//                NSMutableAttributedString.init(string: item)
            
//            str.addAttributes(normalAttr, range: NSRange.init(location: 0, length: str.length))
            
            array.append(str)
            
            height += 5 + 20
        }
        
        height += 10 + 5 + 15
        
        header_height = height
        
        match_message_attr_array = array
    }
    
    static func createAttr(text:String)->NSAttributedString{
        
        let normalAttr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
        let highlightAttr: [NSMutableAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 1, green: 0.12, blue: 0.34,alpha:1.000000)]
        
        let sum = NSMutableAttributedString()
        
        var str = ""
        var number = ""
        var numberBegin = false
        
        for c in text{
            
            if c == "["{
                if str.count > 0{
                    let s = NSMutableAttributedString.init(string: str)
                    s.addAttributes(normalAttr, range: NSRange.init(location: 0, length: s.length))
                    sum.append(s)
                }
                str = ""
                numberBegin = true
            }else if c == "]"{
                
                let nm = NSMutableAttributedString.init(string: number)
                nm.addAttributes(highlightAttr, range: NSRange.init(location: 0, length: nm.length))
                sum.append(nm)
                number = ""
                numberBegin = false
            }else{
                if numberBegin{
                    number.append(c)
                }else{
                    str.append(c)
                }
            }
        }
        
        
        if str.count > 0{
            let s = NSMutableAttributedString.init(string: str)
            s.addAttributes(normalAttr, range: NSRange.init(location: 0, length: s.length))
            sum.append(s)
        }
        
        if number.count > 0{
            let nm = NSMutableAttributedString.init(string: number)
            nm.addAttributes(highlightAttr, range: NSRange.init(location: 0, length: nm.length))
            sum.append(nm)
        }
        
        return sum
    }
}
